import shop from '@/api/shop'

const state  = {
  all:[]
}

const getters = {
  allProducts: state => state.all
}

const mutations = {
  setProducts(state, products){
    state.all = products
  },
  decrementProductInventory(state,{id}){
     let product = ''
     state.all.forEach(element => {
      let ids = element.shopCartListData.find(shopCartList => shopCartList.id === id);
      if (ids) {
        product = ids;
      }
    });
    // console.log('product________-',product)
    product.inventory--
  },
  removeProduct (state, {id}){
    console.log(state,id)
    state.all.forEach(element => {
      let index =  element.shopCartListData.findIndex(added => added.id === id)
      if (index != -1) {
        if (element.shopCartListData.length == 1) { //剩余最后一个数组时 删除父级数组
          let i =  state.all.findIndex(ele => ele.shopId === element.shopId)
          state.all.splice(i, 1)
        }else{  //删除单个数组
          element.shopCartListData.splice(index, 1)
        }         
      }
    });
  }
}
const actions = {
  getAllProducts({commit}){
    shop.getProducts(products=>{
      commit('setProducts',products)
    })
  },
  decrementProductInventory({commit},item){
    commit('decrementProductInventory',item)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
